import {
    Image,
    ScrollView,
    StyleSheet,
    ToastAndroid,
    TouchableOpacity,
    View,
    TextInput,
    Modal,
    Button
} from "react-native";
import {Icon, Text} from "@rneui/themed";
import {pick, types} from "@react-native-documents/picker";
import React, {useEffect, useState} from "react";
import {viewDocument} from "@react-native-documents/viewer";
import ImageViewing from "react-native-image-viewing";
import {getFilePresignedUrl, uploadFileToPresignedUrl} from "../api/file.ts";

interface FileImportProps {
    maxSize: number;
    maxCount: number;
    onFileChange: (file: any[]) => void;
}

interface FileProps {
    // 服务器访问
    url?: string,
    // 手机上的路径
    uri?: string,
    name: string,
    size: string | number,
    type?: string
}

export const FileImport = ({maxSize, maxCount, onFileChange}: FileImportProps) => {
    // 原始文件数据，需首先上传到服务器
    const [file, setFile] = useState<FileProps[]>([]);
    // 已上传到服务器的文件数据
    const [uploadedFile, setUploadedFile] = useState<FileProps[]>([]);
    const [viewerVisible, setViewerVisible] = useState(false);
    const [currentImageIndex, setCurrentImageIndex] = useState(0);
    // 弹窗相关状态
    const [isRenameModalVisible, setRenameModalVisible] = useState(false);
    const [fileToRename, setFileToRename] = useState<{ index: number; name: string } | null>(null);
    const [newBaseName, setNewBaseName] = useState('');
    const [isLocked, setIsLocked] = useState<boolean>(false);

    const handleDelete = (indexToDelete: number) => {
        setFile(currentFiles => currentFiles.filter((_, index) => index !== indexToDelete));
    };

    const imageSources = file
        .filter(item => item.type.includes("image"))
        .map(item => ({uri: item.uri}));

    const openImageViewer = (index: number) => {
        const imageIndex = file.slice(0, index).filter(item => item.type.includes("image")).length;
        setCurrentImageIndex(imageIndex);
        setViewerVisible(true);
    };

    const splitFileName = (fileName: string) => {
        const lastDotIndex = fileName.lastIndexOf('.');
        return {
            baseName: fileName.substring(0, lastDotIndex),
            extension: fileName.substring(lastDotIndex),
        };
    };

    // 打开弹窗并设置初始值
    const openRenameModal = (index: number, currentName: string) => {
        setFileToRename({index, name: currentName});
        const {baseName} = splitFileName(currentName);
        setNewBaseName(baseName);
        setRenameModalVisible(true);
    };

    // 处理重命名确认逻辑
    const handleConfirmRename = () => {
        if (fileToRename === null) return;

        const updatedFiles = file.map((item, index) => {
            if (index === fileToRename.index) {
                const {extension} = splitFileName(item.name);
                const finalName = newBaseName.trim() === '' ? item.name : newBaseName + extension;
                return {...item, name: finalName};
            }
            return item;
        });
        setFile(updatedFiles);

        // 关闭并重置状态
        setRenameModalVisible(false);
        setFileToRename(null);
        setNewBaseName('');
    };

    const uploadFile = (File: FileProps[]) => {
        const data = File.map((i: FileProps) => {
            return {uri: i.uri, name: i.name, type: i.type, size: calSize(Number(i.size))}
        })
        console.log(data)
        data.forEach(async (item: any) => {
            const uploadRes = await getFilePresignedUrl(item.name);
            console.log("fuck", uploadRes)
            uploadFileToPresignedUrl(uploadRes.data.uploadUrl, {
                uri: item.uri,
                type: item.type,
                name: item.name
            }).then((res) => {
                if (res.ok) {
                    const i = {
                        name: item.name,
                        size: item.size,
                        url: uploadRes.data.url,
                    }
                    setUploadedFile([...uploadedFile, i])
                }
            });
        })
    }

    const calSize = (size: number) => {
        if (size < 1024) {
            return size + ' B'
        } else if (size < 1024 * 1024) {
            return (size / 1024).toFixed(2) + ' KB'
        } else if (size < 1024 * 1024 * 1024) {
            return (size / (1024 * 1024)).toFixed(2) + ' MB'
        } else {
            return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
        }
    }

    useEffect(() => {
        if (onFileChange) {
            onFileChange(uploadedFile);
        }
    }, [uploadedFile]);

    const styles = StyleSheet.create({
        label: {
            fontSize: 16,
            fontWeight: '800',
            marginTop: 22,
            marginBottom: 4,
        },
        container: {
            alignSelf: 'center',
            backgroundColor: '#ddd',
            flexDirection: 'column',
            alignItems: 'center',
            borderWidth: 1,
            borderColor: '#888',
            borderStyle: 'dashed',
            borderRadius: 8,
            marginTop: 15,
            marginBottom: 10,
            padding: 15,
            width: '70%',
        },
        description: {
            fontSize: 16,
            color: '#666',
            marginBottom: 15,
            textAlign: 'center',
            fontStyle: 'italic',
        },
        fileItem: {
            flexDirection: 'column',
            marginBottom: 10,
            paddingHorizontal: 20,
            paddingVertical: 15,
            borderRadius: 8,
            borderWidth: 1,
            borderColor: '#888',
        },
        fileNameContainer: {
            flexDirection: 'row',
            alignItems: 'center',
        },
        fileName: {
            fontSize: 18,
            fontWeight: '600',
            marginBottom: 10,
            color: "#888",
            flex: 1,
        },
        fileExtension: {
            borderRadius: 4,
            borderWidth: 1,
            borderColor: "red",
            fontSize: 18,
            paddingHorizontal: 5,
            fontWeight: '600',
            marginBottom: 10,
            color: "red",
        },
        fileText: {
            fontSize: 16,
            fontWeight: '600',
        },
        // 弹窗样式
        modalContainer: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: 'rgba(0, 0, 0, 0.5)',
        },
        modalContent: {
            width: '80%',
            backgroundColor: 'white',
            borderRadius: 10,
            padding: 20,
            alignItems: 'center',
        },
        modalTitle: {
            fontSize: 20,
            fontWeight: 'bold',
            marginBottom: 20,
        },
        renameInputContainer: {
            flexDirection: 'row',
            alignItems: 'center',
            width: '100%',
            marginBottom: 20,
        },
        modalTextInput: {
            flex: 1,
            borderBottomWidth: 1,
            borderColor: '#888',
            fontSize: 16,
            padding: 5,
            height: 50,
        },
        modalFileExtension: {
            fontSize: 16,
            marginLeft: 5,
            color: '#666',
        },
        modalButtonContainer: {
            flexDirection: 'row',
            justifyContent: 'space-around',
            width: '100%',
        },
        lockButton: {
            backgroundColor: '#007AFF', // 一个标准的、清晰的蓝色，代表主要操作
            paddingVertical: 12,       // 上下内边距，让按钮变得“厚实”
            paddingHorizontal: 30,     // 左右内边距
            borderRadius: 8,           // 圆角，让它看起来更柔和
            marginVertical: 20,             // 和其他元素的间距
            alignItems: "center"
        },
        lockButtonText: {
            color: 'white',            // 白色文本在蓝色背景上最清晰
            fontSize: 16,
            fontWeight: 'bold',        // 加粗，强调文本
        }
    })
    return (
        <View>
            <Text style={styles.label}>上传附件</Text>
            {!isLocked && <View>
                <TouchableOpacity
                    style={styles.container}
                    onPress={async () => {
                        try {
                            let pickResult = await pick({
                                allowMultiSelection: true,
                                type: [types.pdf, types.images, types.doc, types.xlsx, types.xls, types.docx]
                            })
                            // 默认最多上传10个文件
                            pickResult.splice(maxCount)

                            // 检查文件大小
                            if (pickResult.length > 0) {
                                const count = pickResult.filter(item => item.size! > maxSize).length;
                                pickResult = pickResult.filter(item => item.size! <= maxSize);
                                if (count) {
                                    ToastAndroid.show(`已排除大小超过${calSize(maxSize)}的文件`, ToastAndroid.SHORT);
                                }
                            }
                            setFile([...file, ...pickResult])
                            console.log(pickResult)
                        } catch (err: any) {
                            console.log(err)
                        }
                    }}
                >
                    <Icon name="add"/>
                    <Text>点击选择文件</Text>
                </TouchableOpacity>
                <Text style={styles.description}>仅支持常见文件类型（doc/docx/xls/xlsx/pdf/jpg/png等），单个文件不超过 20
                    MB，最多上传 10 个文件</Text>
            </View>}

            {file.map((item: FileProps, index: number) => {
                const {baseName, extension} = splitFileName(item.name);
                return (
                    <View style={styles.fileItem} key={index}>
                        <View style={styles.fileNameContainer}>
                            <Text style={styles.fileName} numberOfLines={1}>{baseName}</Text>
                            <Text style={styles.fileExtension}>{extension}</Text>
                            <TouchableOpacity
                                onPress={() => openRenameModal(index, item.name)}
                                style={{marginLeft: 10}}
                                disabled={isLocked}
                            >
                                <Icon name="edit" size={20} color={!isLocked ? "blue" : "grey"}/>
                            </TouchableOpacity>
                        </View>

                        {item.type.includes("image") &&
                            <>
                                <TouchableOpacity onPress={() => openImageViewer(index)}>
                                    <Image
                                        source={{uri: item.url || item.uri}}
                                        style={{
                                            width: 150,
                                            height: 150,
                                            borderRadius: 8,
                                            backgroundColor: '#f5f5f5',
                                            opacity: 1,
                                            marginVertical: 10,
                                        }}
                                        resizeMode="cover"
                                    />
                                </TouchableOpacity>
                            </>
                        }
                        <Text style={styles.fileText}>文件大小：{calSize(item.size)}</Text>
                        <View style={{flexDirection: "row"}}>
                            <TouchableOpacity
                                onPress={() => handleDelete(index)}
                                disabled={isLocked}
                            >
                                <Text
                                    style={[styles.fileText, {
                                        color: isLocked ? "grey" : "red",
                                        fontSize: 14,
                                        marginVertical: 10,
                                        marginRight: 20
                                    }]}>删除</Text>
                            </TouchableOpacity>
                            {!item.type.includes("image") &&
                                <TouchableOpacity
                                    onPress={() => {
                                        viewDocument({uri: item.uri, mimeType: item.type}).then(r => {
                                            console.log(r)
                                        })
                                    }}
                                >
                                    <Text
                                        style={[styles.fileText, {
                                            color: "blue",
                                            fontSize: 14,
                                            marginRight: 20,
                                            marginTop: 10
                                        }]}>预览文件
                                    </Text>
                                </TouchableOpacity>
                            }
                        </View>
                    </View>
                )
            })}

            {(file.length > 0 && !isLocked) && <><Text>若已确定附件无误后，点击按钮锁定附件</Text><TouchableOpacity
                style={styles.lockButton}
                onPress={() => {
                    setIsLocked(true)
                    uploadFile(file)
                }}>
                <Text style={styles.lockButtonText}>锁定附件</Text>
            </TouchableOpacity></>
            }

            <ImageViewing
                images={imageSources}
                imageIndex={currentImageIndex}
                visible={viewerVisible}
                onRequestClose={() => setViewerVisible(false)}
            />

            {/* 重命名弹窗 */}
            <Modal
                transparent={true}
                animationType="fade"
                visible={isRenameModalVisible}
                onRequestClose={() => setRenameModalVisible(false)}
            >
                <View style={styles.modalContainer}>
                    <View style={styles.modalContent}>
                        <Text style={styles.modalTitle}>修改文件名</Text>
                        <View style={styles.renameInputContainer}>
                            <TextInput
                                style={styles.modalTextInput}
                                value={newBaseName}
                                onChangeText={setNewBaseName}
                                autoFocus={true}
                            />
                            <Text style={styles.modalFileExtension}>
                                {fileToRename ? splitFileName(fileToRename.name).extension : ''}
                            </Text>
                        </View>
                        <View style={styles.modalButtonContainer}>
                            <TouchableOpacity
                                style={{paddingVertical: 10, paddingHorizontal: 30, backgroundColor: '#999'}}
                                onPress={() => setRenameModalVisible(false)}>
                                <Text style={{color: "white"}}>取消</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={{paddingVertical: 10, paddingHorizontal: 30, backgroundColor: '#1F93F3'}}
                                onPress={handleConfirmRename}>
                                <Text style={{color: "white"}}>确认</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>
        </View>
    )
}